package it.eng.area118.mdocommon.android.util;

import it.eng.area118.mdocommon.android.log.BasicLogger;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.format.Formatter;

public class NetworkUtility {

	private static final String TAG = "NetworkUtility";

	public static String getLocalIpv4Address(WifiManager wifiManager) {
		// WifiManager wifiManager = (WifiManager)
		// getSystemService(Context.WIFI_SERVICE);
		WifiInfo wifiInfo = wifiManager.getConnectionInfo();
		int ipAddress = wifiInfo.getIpAddress();
		return Formatter.formatIpAddress(ipAddress);
	}

	public static String getLocalIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				String ip = "DEFAULT";
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();

					if (inetAddress.toString().contains(".")) {
						ip = inetAddress.getHostAddress().toString();
					}
					if (!inetAddress.isLoopbackAddress()) {

						if (ip.equals("10.0.2.15")) {
							ip = "127.0.0.1";
						}

					}
				}
				BasicLogger.writeLog(TAG, "IP FOUND IS: " + ip);
				return ip;
			}
		} catch (SocketException ex) {
			BasicLogger.writeLog(TAG, ex.toString());
		}
		return null;
	}
}
